package com.hos.operation.api;


import com.gexin.rp.sdk.base.uitls.MD5Util;
import com.hos.db.entity.ArtEntity;
import com.hos.db.entity.SmsEntity;
import com.hos.db.entity.UserDocEntity;
import com.hos.db.entity.UserPatsEntity;
import com.hos.db.entity.UserSysEntity;
import com.hos.db.manager.ArtManager;
import com.hos.db.manager.DocsManager;
import com.hos.db.manager.PatsManager;
import com.hos.db.manager.SMSManager;
import com.hos.db.manager.SysManager;
import com.hos.net.DictionariesFileService;
import com.hos.net.DictionariesIllService;
import com.hos.net.DictionariesSysService;
import com.hos.net.req.BaseReq;
import com.hos.net.req.UserSearchReq;
import com.hos.net.req.art.ArtCreateReq;
import com.hos.net.req.art.ArtDeleteReq;
import com.hos.net.req.art.ArtStateReq;
import com.hos.net.req.art.ArtUpdateReq;
import com.hos.net.req.doc.DocUpdateReq;
import com.hos.net.req.pat.PatUpdateReq;
import com.hos.net.req.sms.SmsReq;
import com.hos.net.req.sys.PwdRestReq;
import com.hos.net.req.sys.SysLoginReq;
import com.hos.net.req.sys.SysRegisterReq;
import com.hos.net.res.BaseResponse;
import com.hos.net.res.MsgHint;
import com.hos.net.res.PageData;
import com.hos.net.res.loading.Upload7NRes;
import com.hos.operation.manager.ConstantData;
import com.hos.operation.manager.Yun7NManager;
import com.hos.utile.DLog;
import com.hos.utile.JsonUtile;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

//系统
@Controller
public class ApiSysController extends ApiBaseCommunal {

    @RequestMapping(value = "/sys", method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String app(HttpServletRequest request, @RequestBody String json) {
        BaseReq req = isVerifyDataJson(request, json,"sys");
        if (!req.isVerify) {
            return req.errorMsg;
        }
        String service = req.service;
        String response = "";
        switch (service) {
            case DictionariesSysService.HOS_SYS_REG:
                //管理员注册
                SysRegisterReq regReq = (SysRegisterReq) JsonUtile.json2Obj(json, SysRegisterReq.class);

                if (!regReq.isVerifyParameter()) {
                    return regReq.hint;
                }
                response = SysManager.getInstance()
                        .sysRegister(getJdbcTemplate(), regReq);
                break;
            case DictionariesSysService.HOS_SYS_LOGIN:
                //登录
                SysLoginReq loginReq = (SysLoginReq) JsonUtile.json2Obj(json, SysLoginReq.class);

                if (!loginReq.isVerifyParameter()) {
                    return loginReq.hint;
                }
                response = SysManager.getInstance()
                        .sysLoginReq(getJdbcTemplate(),
                                loginReq.account, loginReq.pwd);
                break;
            case DictionariesSysService.HOS_SYS_SMS_PWD_REAT:
                //发送重置密码的验证码
                SmsReq smsReq = (SmsReq) JsonUtile.json2Obj(json, SmsReq.class);
                if (!smsReq.isVerifyParameter("2")) {
                    return smsReq.hint;
                }
                UserSysEntity user = SysManager.getInstance().getUserForPhone(getJdbcTemplate(), smsReq.phone);
                if (user == null) {
                    response = new MsgHint("-1", "没有找到相应的账号").toJson();
                    break;
                }
                //发送验证码
                response = SMSManager.getInstance().smsSend(getJdbcTemplate(), smsReq);
                break;
            case DictionariesSysService.HOS_SYS_PWD_REAT:
                //重置密码
                PwdRestReq pwdRestReq = (PwdRestReq) JsonUtile.json2Obj(json, PwdRestReq.class);
                //
                if (!pwdRestReq.isVerifyParameter()) {
                    return pwdRestReq.hint;
                }
                SmsEntity sms = SMSManager.getInstance().getSms(getJdbcTemplate(),
                        pwdRestReq.phone, pwdRestReq.type, pwdRestReq.code);
                //没有发送验证码
                if (sms == null) {
                    response = new MsgHint("-1", "验证码无效").toJson();
                    DLog.e("没有发送验证码");
                    break;
                }
                //已经使用过了
                if (sms.isSmsIsVerifyIs()) {
                    response = new MsgHint("-1", "验证码无效").toJson();
                    DLog.e("已经使用过了");
                    break;
                }
                //超时
                long time = new Date().getTime() - sms.getSmsSendTime().getTime();
                if (time > ConstantData.SMS_OUT_TIME) {
                    response = new MsgHint("-1", "验证码无效").toJson();
                    SMSManager.getInstance().deleteSms(getJdbcTemplate(), sms.getSmsId());
                    DLog.e("验证码超时");
                    break;
                }
                //获取用户
                user = SysManager.getInstance().getUserForPhone(getJdbcTemplate(), pwdRestReq.phone);
                if (user == null) {
                    response = new MsgHint("-1", "没有找到相应的账号").toJson();
                    break;
                }
                String pwd = MD5Util.getMD5Format(pwdRestReq.pwd);
                if (pwd.equals(user.getSysPwd())) {
                    response = new MsgHint("-1", "新密码不能和旧密码相同").toJson();
                    break;
                }
                // 修改密码成功
                boolean isSucceed = SysManager.getInstance().updatePwdRest(getJdbcTemplate(), pwdRestReq.phone,
                        pwdRestReq.pwd);
                if (isSucceed) {
                    //删除验证码
                    SMSManager.getInstance().deleteSms(getJdbcTemplate(), sms.getSmsId());
                    response = new MsgHint("0", "密码修改成功").toJson();
                    break;
                }
                response = new MsgHint("-1", "密码修改失败").toJson();
                break;
            case DictionariesSysService.HOS_SYS_PATS:
                //搜索患者
                boolean isverify = verifyToken(req.token);
                if (!isverify) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                UserSearchReq patSearchReq = (UserSearchReq) JsonUtile.json2Obj(json, UserSearchReq.class);

                List<UserPatsEntity> pats = PatsManager.getInstance().getPats(getJdbcTemplate(),
                        patSearchReq.key, req.pageNo, req.pageSize, true);
                int patSize = pats.size();
                BaseResponse baseRes = new BaseResponse();
                PageData pageData = new PageData();
                if (patSize > req.pageSize) {
                    //有下一页
                    pats.remove(patSize - 1);
                    pageData.hasNextPage = true;
                }
                pageData.pageNo = req.pageNo;
                pageData.pageSize = pats.size();
                pageData.total = PatsManager.getInstance().getPats(getJdbcTemplate(), patSearchReq.key);
                baseRes.pageData = pageData;
                baseRes.list = pats;
                response = JsonUtile.obj2Json(baseRes);
                break;
            case DictionariesSysService.HOS_SYS_PATS_UPDATE:
                //修改患者信息
                isverify = verifyToken(req.token);
                if (!isverify) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                PatUpdateReq patUpdateReq = (PatUpdateReq) JsonUtile.json2Obj(json, PatUpdateReq.class);
                if (!patUpdateReq.isVerifyParameter()) {
                    return patUpdateReq.hint;
                }
                response = PatsManager.getInstance().updateUserReq(getJdbcTemplate(), patUpdateReq);
                break;

            case DictionariesSysService.HOS_SYS_DOCS:
                ////获取医生列表,搜索医生
                isverify = verifyToken(req.token);
                if (!isverify) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                UserSearchReq docSearchReq = (UserSearchReq) JsonUtile.json2Obj(json, UserSearchReq.class);
                //
                List<UserDocEntity> docs = DocsManager.getInstance().getDocs(getJdbcTemplate(),
                        docSearchReq.key, true, req.pageNo, req.pageSize, true);
                patSize = docs.size();
                baseRes = new BaseResponse();
                pageData = new PageData();
                if (patSize > req.pageSize) {
                    //有下一页
                    docs.remove(patSize - 1);
                    pageData.hasNextPage = true;
                }
                pageData.pageNo = req.pageNo;
                pageData.pageSize = docs.size();
                pageData.total = DocsManager.getInstance().getDocs(getJdbcTemplate(), docSearchReq.key);
                baseRes.pageData = pageData;
                baseRes.list = docs;
                response = JsonUtile.obj2Json(baseRes);
                break;
            case DictionariesSysService.HOS_SYS_DOCS_UPDATE:
                //修改医生信息
                isverify = verifyToken(req.token);
                if (!isverify) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                DocUpdateReq docUpdateReq = (DocUpdateReq) JsonUtile.json2Obj(json, DocUpdateReq.class);
                if (!docUpdateReq.isVerifyParameter()) {
                    return docUpdateReq.hint;
                }
                response = DocsManager.getInstance().updateUserReq(getJdbcTemplate(), docUpdateReq);
                break;
            case DictionariesSysService.HOS_SYS_ARTS:
                //获取文章
                user = verifyTokenUser(req.token);
                if (user == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                List<ArtEntity> arts = ArtManager.getInstance().getArts(getJdbcTemplate(),
                        user.getSysId(), req.pageNo, req.pageSize, true);
                patSize = arts.size();
                baseRes = new BaseResponse<UserPatsEntity>();
                pageData = new PageData();
                if (patSize > req.pageSize) {
                    //有下一页
                    arts.remove(patSize - 1);
                    pageData.hasNextPage = true;
                }
                pageData.pageNo = req.pageNo;
                pageData.pageSize = arts.size();
                pageData.total = ArtManager.getInstance().getArts(getJdbcTemplate(), user.getSysId());
                baseRes.pageData = pageData;
                baseRes.list = arts;
                response = JsonUtile.obj2Json(baseRes);
                break;
            case DictionariesSysService.HOS_SYS_ART_ADD:
                //添加文章
                user = verifyTokenUser(req.token);
                if (user == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                ArtCreateReq artAddReq = (ArtCreateReq) JsonUtile.json2Obj(json, ArtCreateReq.class);
                response = ArtManager.getInstance().artAddReq(getJdbcTemplate(), user, artAddReq);
                break;
            case DictionariesSysService.HOS_SYS_ART_DELTE:
                //删除文章
                user = verifyTokenUser(req.token);
                if (user == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                ArtDeleteReq artDeleteReq = (ArtDeleteReq) JsonUtile.json2Obj(json, ArtDeleteReq.class);
                isverify = artDeleteReq.isVerifyParameter();
                if (!isverify) {
                    response = artDeleteReq.hint;
                    break;
                }
                response = ArtManager.getInstance().deleteArtReq(getJdbcTemplate(),
                        user.getSysId(), artDeleteReq);
                break;
            case DictionariesSysService.HOS_SYS_ART_UPDATE:
                //修改文章
                user = verifyTokenUser(req.token);
                if (user == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                ArtUpdateReq artUpdateReq = (ArtUpdateReq) JsonUtile.json2Obj(json, ArtUpdateReq.class);
                isverify = artUpdateReq.isVerifyParameter();
                if (!isverify) {
                    response = artUpdateReq.hint;
                    break;
                }
                response = ArtManager.getInstance().updateArtReq(getJdbcTemplate(),
                        user.getSysId(), artUpdateReq);
                break;

            case DictionariesSysService.HOS_SYS_ART_STATE:
                //修改文章状态
                user = verifyTokenUser(req.token);
                if (user == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                ArtStateReq artStateReq = (ArtStateReq) JsonUtile.json2Obj(json, ArtStateReq.class);
                isverify = artStateReq.isVerifyParameter();
                if (!isverify) {
                    response = artStateReq.hint;
                    break;
                }
                response = ArtManager.getInstance().updateArtReq(getJdbcTemplate(),
                        user.getSysId(), artStateReq.artId, artStateReq.state, artStateReq.issue);
                break;
            case DictionariesSysService.HOS_SYS_FILE_TOKEN:
                //获取7牛上传的token
                String token = Yun7NManager.getInstance().getToken();
                BaseResponse res = new BaseResponse();
                Upload7NRes upload7NRes = new Upload7NRes();
                upload7NRes.token = token;
                res.obj = upload7NRes;
                response = res.toJson("0", "获取上传凭证成功");
                break;
            default:
                user = verifyTokenUser(req.token);
                if (user == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                if (DictionariesIllService.isIllService(service)) {
                    response = onIll(service, json, null, null, user);
                    break;
                }
                if (DictionariesFileService.isUplaodingService(service)) {
                    response = onUploading(service, json, null, null, user);
                    break;
                }
                response = new MsgHint("请求未定义").toJson();
                break;
        }
        return response;
    }

    //需要登陆才能操作
    private boolean verifyToken(String token) {
        return verifyTokenUser(token) != null;
    }

    private UserSysEntity verifyTokenUser(String token) {
        return SysManager.getInstance().verifyTokenUser(getJdbcTemplate(), token);
    }

    //校验分页查询数据
    private boolean verifyPaging(BaseReq req) {
        int pageNo = req.pageNo;
        int pageSize = req.pageSize;
        if (pageNo == 0) {
            return false;
        }
        if (pageSize <= 0) {
            pageSize = 30;
        }
        req.pageSize = pageSize;
        return true;
    }
}
